package com.eqs.enterprisequestionnaire.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eqs.enterprisequestionnaire.mapper.OptionMapper;
import com.eqs.enterprisequestionnaire.mapper.QuestionMapper;
import com.eqs.enterprisequestionnaire.model.enums.QuestionEnum;
import com.eqs.enterprisequestionnaire.model.pojo.Option;
import com.eqs.enterprisequestionnaire.model.pojo.Question;
import com.eqs.enterprisequestionnaire.model.pojo.Questionnaire;
import com.eqs.enterprisequestionnaire.service.HistoryService;
import com.eqs.enterprisequestionnaire.service.OptionService;
import com.eqs.enterprisequestionnaire.service.QuestionService;
import com.eqs.enterprisequestionnaire.service.QuestionnaireService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class QuestionImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {
    @Autowired
    QuestionMapper questionMapper;
    @Autowired
    OptionMapper optionMapper;
    @Autowired
    private OptionService optionService;
    @Autowired
    private HistoryService historyService;

    public Question getQuestionAfterCreat(Question question){
        QueryWrapper<Question> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("questionnaire_id",question.getQuestionnaireId())
                .eq("type",question.getType())
                .eq("content",question.getContent());
        return questionMapper.selectOne(queryWrapper);
    }
    public void insertQuestion(Integer questionnaireId, String type,String content){
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("questionnaire_id", questionnaireId);
        int count = Math.toIntExact(questionMapper.selectCount(queryWrapper));
        boolean isEmpty = (count == 0);

        Question question = new Question();
        question.setQuestionnaireId(questionnaireId);
        question.setType(type);
        question.setContent(content);

        if (isEmpty) {
            question.setOrdination(1);
            questionMapper.insert(question);
        } else {
            questionMapper.insert(question);
            Integer newOrdination = getQuestionOrdination(question.getId());
            question.setOrdination(newOrdination);
            questionMapper.updateById(question);
        }
    }
    public Integer getQuestionOrdination(Integer questionId) {
        // 根据 questionId 找到对应的 questionnaire 对象
        Questionnaire questionnaire = historyService.getQuestionnaireByQuestionId(questionId);
        if (questionnaire == null) {
            throw new IllegalArgumentException("Invalid questionnaireId: " + questionnaire.getQuestionnaireId());
        }

        // 获取该 Questionnaire 对应的所有 Question 对象
        List<Question> questions = historyService.getListQuestionByQuestionnaireId(questionnaire.getQuestionnaireId());

        // 查找所有 Question 对象的最大 index 值
        int maxOrdination = 0;
        for (Question q : questions) {
            if (q.getOrdination() != null && q.getOrdination() > maxOrdination) {
                maxOrdination = q.getOrdination();
            }
        }

        // 设置当前 question 的 index 值
        return maxOrdination + 1;
    }

    public Question selectByQuestionId(Integer questionId){
        return questionMapper.selectById(questionId);
    }

    public void updateQuestion(@NotNull Question question){
        Question existingQuestion = selectByQuestionId(question.getQuestionId());
        if (existingQuestion != null) {
            // 使用 BeanUtils.copyProperties 进行属性赋值
            BeanUtils.copyProperties(question, existingQuestion);//,getNullPropertyNames(question)
            // 更新数据库中的用户信息
            questionMapper.updateById(existingQuestion);
        } else {
            throw new RuntimeException("Question not found");
        }
    }
    @NotNull
    private String[] getNullPropertyNames(Question source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    public void deleteQuestion(Integer questionId){
        /*QueryWrapper<Question> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",questionId);
        questionMapper.delete(queryWrapper);
        QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("question_id", questionId);
        answerMapper.delete(queryWrapper);*/
        questionMapper.deleteById(questionId);

        // 删除与此问题相关的所有选项
        QueryWrapper<Option> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("question_id", questionId);

    }
    //显示默认选项
    public List<Option> displayOption(Question question){
        int questionType = getQuestionType(question);
        List<Option> options = new ArrayList<>();
        int currentMaxId = optionService.selectMaxId();
        switch (questionType) {
            case 1: // SINGLE_CHOICE
            case 2: // MULTIPLE_CHOICE
                for (int i = 1; i <= 4; i++) {
                    Option option_12 = new Option();
                    option_12.setId(currentMaxId + i);
                    option_12.setContent("Option " + (currentMaxId + i));
                    option_12.setQuestionId(question.getId());
                    options.add(option_12);
                    optionMapper.insert(option_12);
                }
                break;
            case 3: // SHORT_ANSWER
            case 5: // TEXTAREA
                Option option_35 = new Option();
                option_35.setId(currentMaxId + 1);
                option_35.setContent("Short answer");
                option_35.setQuestionId(question.getId());
                options.add(option_35);
                optionMapper.insert(option_35);
                break;
            case 4: // DROPDOWN
            case 6: //SortQuestion
                for (int i = 1; i <= 3; i++) {
                    Option option_46 = new Option();
                    option_46.setId(currentMaxId + i);
                    option_46.setContent("Option " + (currentMaxId + i));
                    option_46.setQuestionId(question.getId());
                    options.add(option_46);
                    optionMapper.insert(option_46);
                }
                break;
            case 7: // LEVELQUESTION
                Option option_7 = new Option();
                option_7.setId(currentMaxId + 1);
                option_7.setContent("程度（由低到高）");
                option_7.setQuestionId(question.getId());
                options.add(option_7);
                optionMapper.insert(option_7);
                break;
            default:
                throw new IllegalArgumentException("Unknown question type: " + questionType);
        }
        return options;
    }

    public int getQuestionType(Question question) {
        String type = question.getType();
        QuestionEnum questionEnum = QuestionEnum.fromType(type);

        switch (questionEnum) {
            case SINGLE_CHOICE:
                return 1;
            case MULTIPLE_CHOICE:
                return 2;
            case SHORT_ANSWER:
                return 3;
            case DROPDOWN:
                return 4;
            case TEXTAREA:
                return 5;
            case SORTQUESTION:
                return 6;
            case LEVELQUESTION:
                return 7;
            default:
                throw new IllegalArgumentException("Unknown question type: " + questionEnum);
        }
    }
}
